﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="CertificateHelper.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace Common
{
    using System.Security.Cryptography.X509Certificates;

    public static class CertificateHelper
    {
         public static X509Certificate2 FindCertificate(X509FindType findType, string str)
         {
             var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

             try
             {
                 certificateStore.Open(OpenFlags.ReadOnly);

                 var certificateCollection = certificateStore.Certificates.Find(findType, str, false);
                 if (certificateCollection.Count != 0)
                 {
                     return certificateCollection[0];        
                 }
             }
             finally
             {
                 certificateStore.Close();
             }

             return null;
         }

         public static X509Certificate2 FindCertificate(StoreName storeName, StoreLocation storeLocation, X509FindType findType, string str)
         {
             var certificateStore = new X509Store(storeName, storeLocation);

             try
             {
                 certificateStore.Open(OpenFlags.MaxAllowed);

                 var certificateCollection = certificateStore.Certificates.Find(findType, str, false);
                 if (certificateCollection.Count != 0)
                 {
                     return certificateCollection[0];        
                 }
             }
             finally
             {
                 certificateStore.Close();
             }

             return null;
         }
    }
}